<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <div :style="{ marginBottom: '16px' }">
          <a-form layout="inline">
            <a-row :gutter="24">
              <a-col
                :md="6"
                :sm="16">
                <a-form-item label="选择年份">
                  <a-select
                    show-search
                    v-model="year"
                    placeholder="请选选择年份">
                    <a-select-option
                      v-for="i in years"
                      :key="i">
                      {{ i }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col
                :md="6"
                :sm="16">
                <a-form-item label="选择版本">
                  <a-select
                    show-search
                    v-model="version"
                    placeholder="请选择版本">
                    <a-select-option
                      v-for="i in versions"
                      :key="i">
                      {{ i }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col
                :md="4"
                :sm="16">
                <div>
                  当前毛利去除率：
                  <a-input-number
                    v-show="rateEdit"
                    style="margin-right: 8px;margin-left: 8px;width: 80px"
                    placeholder="请输入毛利率(%)"
                    v-model="editMarginRate" />
                  <span
                    style="margin-right: 8px;margin-left: 8px;width: 80px"
                  >{{ marginRemovalRate }}%</span>
                </div>
              </a-col>
              <a-col :md="8" style="text-align: right;padding-right: 60px" >
                <a-button
                  @click="() => { this.copyVisible = true }"
                  style="margin-right: 10px">复制</a-button>
                <a-button
                  type="primary"
                  @click="handleAdd">新建</a-button>
                <a-button
                  type="dash"
                  style=" margin-left: 8px "
                  @click="() => { this.getYears() }">重置</a-button>
              </a-col>
            </a-row>
          </a-form>
          <a-row :gutter="24">
            <a-col
              :md="24"
              :sm="24">
              <div>
                版本备注：
                <a-input
                  v-show="noteEdit"
                  style="margin-right: 8px;margin-left: 8px;width: 380px"
                  placeholder="请输入版本备注"
                  v-model="editNote" />
                <span
                  style="margin-right: 8px;margin-left: 8px;width: 80px"
                  v-show="!noteEdit">{{ note }}</span>
                <a-button
                  v-show="!noteEdit"
                  @click="() => { this.noteEdit = true }"
                  type="primary">编辑</a-button>
                <a-button
                  v-show="noteEdit"
                  @click="handleEditNote"
                  type="primary">提交</a-button>
              </div>
            </a-col>
          </a-row>
        </div>
        <a-tabs
          :activeKey="job1"
          @change="ind => { this.job1 = ind }">
          <a-tab-pane
            v-for="i in jobPartMent"
            :key="i.value"
            :tab="`${i.label}`" />
        </a-tabs>
        <a-tabs
          :activeKey="job2"
          @change="ind => { this.job2 = ind }">
          <a-tab-pane
            v-for="pane in panes"
            :key="pane.value"
            :tab="pane.label" />
        </a-tabs>
      </div>
      <div>
        <a-row>
          <a-col
            :offset="16"
            :md="8">
            <div style="float: right; margin: 0 60px 20px 0;">
              <a-button
                @click="handleEdit"
                v-if="!isEdit"
                style="margin-right: 10px">编辑</a-button>
              <a-button
                @click="() => { this.isEdit = false }"
                v-if="isEdit"
                style="margin-right: 10px">取消</a-button>
              <a-button
                type="primary"
                @click="handleSubmit">提交</a-button>
            </div>
          </a-col>
        </a-row>
      </div>
      <div style="min-width: 1200px">
        <yewu-cards
          :isEdit="isEdit"
          v-if="showCard"
          :job2="job2"
          :yewuConfig="yewuConfig"
          ref="yewu"
          v-show="job1 === 1" />
        <engine-cards
          :isEdit="isEdit"
          ref="engine"
          v-if="showCard"
          :engineConfig="engineConfig"
          v-show="job1 === 2" />
        <prod-cards
          :isEdit="isEdit"
          v-if="showCard"
          ref="prod"
          :prodConfig="prodConfig"
          v-show="job1 === 3" />
        <admin-cards
          :isEdit="isEdit"
          v-if="showCard"
          ref="admin"
          :adminConfig="adminConfig"
          v-show="job1 === 4" />
        <DemoCard
          v-if="job1 ==1 || job1 === 2"
          title="模拟"
          :performanceConfigId="performanceConfigId"
          :job1="job1"
          :job2="job2"
        />
        <SCDemoCard
          v-if="job1 === 3"
          title="模拟"
          :prodConfig="prodConfig"
        />
      </div>
    </a-card>

    <create-form
      ref="createModal"
      :visible="visible"
      :year="nextYear"
      :version="nextVersion"
      @ok="handleOk"
      @cancel="handleCancel" />
    <copy-form
      ref="copyModal"
      :visible="copyVisible"
      :years="years"
      :versions="versions"
      @ok="handleCopyOk"
      @cancel="() => { this.copyVisible = false }" />
  </page-header-wrapper>
</template>

<script>
import YewuCards from './tables/YewuCards'
import EngineCards from './tables/EngineCards'
import ProdCards from './tables/ProdCards'
import AdminCards from './tables/AdminCards'
import { columns, prodConfig, adminConfig, yewuConfig, engineConfig } from './mock.js'
import CreateForm from './modules/CreateForm'
import CopyForm from './modules/CopyForm'
import { yewuToTable, tableToYewu, enginerToTable, tableToEnginer, prodToTable, tableToProd } from './tables/config'
import {
  getPerformanceConfigInfo,
  getYearsVersion,
  savePerformanceConfigInfo,
  updatePerformanceConfigInfo,
  simulationPerformance,
  updateRemoval,
  copyPerformance
} from '@/api/performanceConfig'
import lodash from 'lodash'
import DemoCard from './tables/compontents/DemoCard'
import SCDemoCard from './tables/compontents/SCDemoCard'
export default {
  name: 'TableList',
  components: {
    YewuCards,
    EngineCards,
    ProdCards,
    AdminCards,
    CreateForm,
    DemoCard,
    SCDemoCard,
    CopyForm
  },
  data () {
    this.columns = columns
    this.yewuConfig = yewuConfig
    this.engineConfig = engineConfig
    this.prodConfig = prodConfig
    this.adminConfig = adminConfig
    return {
      copyVisible: false,
      job1: 1,
      job2: 1,
      // 毛利去除率
      marginRemovalRate: undefined,
      editMarginRate: undefined,
      rateEdit: false,
      performanceConfigIds: undefined,
      // 版本备注
      note: undefined,
      editNote: undefined,
      noteEdit: false,

      isEdit: false,
      visible: false,
      years: [],
      versions: [],
      year: undefined,
      showCard: false,
      actualYearVersion: [],
      performanceConfigId: undefined,
      version: undefined,
      nextYear: undefined,
      nextVersion: undefined,
      panes: [
        { label: '全职业务员', value: 1 },
        { label: '兼职业务员', value: 2 }
      ],
      type: [
        { label: '兼职', value: 1 },
        { label: '全职', value: 2 }
      ],
      jobPartMent: [
        { label: '业务提成规则', value: 1 },
        { label: '工程提成规则', value: 2 },
        { label: '生产提成规则', value: 3 },
        { label: '行政管理奖金', value: 4 }
      ]
    }
  },
  watch: {
    job1: function (job1) {
      this.isEdit = false
      switch (job1) {
        case 1:
          this.job2 = 1
          this.panes = [
            { label: '全职业务员', value: 1 },
            { label: '兼职业务员', value: 2 }
          ]
          break
        case 2:
          this.job2 = 3
          this.panes = [{ label: '项目经理', value: 3 }]
          break
        case 3:
          this.job2 = undefined
          this.panes = [
            { label: '生产组', value: undefined }
            // { label: '策划组', value: 4 },
            // { label: 'UI设计&动效创意组 ', value: 5 },
            // { label: '程序组 ', value: 6 },
            // { label: '内容组(定制软件)', value: 7 },
            // { label: '硬件开发组(定制硬件)', value: 8 }
          ]
          break
        case 4:
          this.job2 = 9
          this.panes = [{ label: '行政管理', value: 9 }]
          break
      }
    },
    job2: function (job2) {
      this.isEdit = false
      this.getCurPerform({ job2 })
    },
    version: function (version) {
      this.isEdit = false
      this.getCurPerform({ version })
    },
    year: function (year) {
      this.isEdit = false
      this.versions = this.actualYearVersion.find(item => item.year === year).version || []
      const targetV = this.versions
      this.version = targetV ? lodash.last(this.versions) : undefined

      this.getCurPerform({ year })
    }
  },
  created () {
    // this.mockData = mockData
  },
  mounted () {
    this.getYears()
  },
  methods: {
    // 复制绩提交
    handleCopyOk (param) {
      const { version, year } = param || {}
      if (!version || !year) {
        this.$message.error('参数不全')
        return
      }
      copyPerformance({ version, year }).then(res => {
        this.getYears()
        this.copyVisible = false
      })
    },
    handleEditNote () {
      updateRemoval({ year: this.year,
      version: this.version,
      marginRemovalRate: (this.marginRemovalRate / 100).toFixed(6),
      note: this.editNote }).then(() => {
        this.editMarginRate = false
        this.rateEdit = false
        this.getCurPerform().then(() => {
          this.noteEdit = false
          this.$message.success('更新成功')
        })
      })
    },
    updateInfo (param) {
      if (this.performanceConfigId || this.performanceConfigIds) {
        return updatePerformanceConfigInfo({
          performanceConfigId: this.performanceConfigId,
          // 只有生产提成更新还有 performanceConfigIds
          performanceConfigIds: this.performanceConfigIds,
          job1: this.performanceConfigIds ? 3 : undefined,
          ...param
        })
      } else {
        return savePerformanceConfigInfo({
          year: this.year,
          version: this.version,
          job1: this.job1,
          job2: this.job2,
          ...param
        })
      }
    },
    // 刷新绩效数据
    getCurPerform (param) {
      this.showCard = false
      return getPerformanceConfigInfo({
        job2: this.job2,
        job1: this.job1,
        year: this.year,
        version: this.version,
        ...param
      }).then(res => {
        this.performanceConfigId = res['data'] ? res.data.performanceConfigId : undefined
        // 赋值毛利去除率
        this.marginRemovalRate = res['data'] ? res.data.marginRemovalRate * 100 : undefined
        this.editMarginRate = this.marginRemovalRate
        this.performanceConfigIds = res.data.performanceConfigIds
        // 赋值版本备注
        this.note = res['data'] ? res.data.note : undefined
        this.editNote = this.note

        switch (this.job1) {
          case 1:
            this.yewuConfig = tableToYewu(res.data)
            this.showCard = true
            break
          case 2:
            this.engineConfig = tableToEnginer(res.data)
            this.simulation()
            this.showCard = true
            break
          case 3:
            this.prodConfig = tableToProd(res.data)
            this.showCard = true
            break
          case 4:
            const { ext1 } = res.data || {}
            this.adminConfig = { rate: ext1 }
            this.showCard = true
            break
        }
      })
    },
    getYears () {
      getYearsVersion().then(res => {
        this.years = res.data.actualYearVersion.map(item => item.year)
        this.actualYearVersion = res.data.actualYearVersion
        this.year = this.years[0]
        const versions = this.actualYearVersion.find(item => item.year === this.year).version || []
        this.version = lodash.last(versions)
        this.versions = versions
        this.nextVersion = res.data.nextYearVersion.version
        this.nextYear = res.data.nextYearVersion.year
      })
    },
    handleCancel () {
      this.visible = false
      this.getYears()
    },
    handleAdd () {
      this.visible = true
    },
    simulation (param) {
      const performanceConfigId = this.performanceConfigId
      performanceConfigId &&
        simulationPerformance({
          performanceConfigId,
          contractMoney: '100000',
          contractMoneyHardware: '5000',
          contractMoneySoftware: '5000',
          grossRate: 0.2,
          ...param
        })
    },
    handleOk () {
      this.visible = false
      this.getYears()
    },
    handleSubmit () {
      if (this.isEdit) {
        switch (this.job1) {
          case 1:
            const yewuConfig = this.$refs.yewu.getConfig()
            let param = yewuToTable(yewuConfig, this.job2 === 2)
            if (!param) {
              this.$message.error('请正确填写参数')
              return
            }
            this.updateInfo(param).then(() => {
              // this.yewuConfig = yewuConfig
              this.getCurPerform()
            })
            break
          case 2:
            const engineConfig = this.$refs.engine.getConfig()
            param = enginerToTable(engineConfig)
            if (!param) {
              this.$message.error('请正确填写参数')
              return
            }
            this.updateInfo(param).then(() => {
              // this.engineConfig = engineConfig
              this.getCurPerform()
            })
            break
          case 3:
            const prodConfig = this.$refs.prod.getConfig()
            param = prodToTable(prodConfig)
            if (!param) {
              this.$message.error('请正确填写参数')
              return
            }
            this.updateInfo(param).then(() => {
              // this.prodConfig = prodConfig
              this.getCurPerform()
            })
            break
          case 4:
            const adminConfig = this.$refs.admin.getConfig()
            if (!adminConfig['rate']) {
              this.$message.error('请正确填写参数')
              return
            }
            this.updateInfo({ ext1: adminConfig.rate }).then(() => {
              // this.adminConfig = adminConfig
              this.getCurPerform()
            })
            break
        }
      }
      this.isEdit = false
    },
    handleEdit (record) {
      if (!this.isEdit) {
        this.isEdit = true
      }
    }
    // filterOption (input, option) {
    //   return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    // }
  }
}
</script>
<style lang="less" scoped>
/deep/.ant-input-number {
  // width: fit-content;
  width: 100%;
}
/deep/.ant-input-number-handler-wrap{
  display: none;
}
/deep/.ant-card-grid {
  padding: 24px 0;
}
</style>
